package me.miencraft.plugin.superlobby.util;

import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;

/**
 * @author langle__
 * @version 1.0
 */
@Getter
public class CommandEntry {

    private final CommandType type;
    private final String command;

    public CommandEntry(CommandType type, String command) {
        this.type = type;
        this.command = command;
    }

    public void execute(Player player) {
        String replace = command.replace("{player}", player.getName());
        if (type == CommandType.Player) {
            Bukkit.dispatchCommand(player, replace);
        } else if (type == CommandType.Op) {
            boolean playerOp = player.isOp();
            player.setOp(true);
            Bukkit.dispatchCommand(player, replace);
            player.setOp(playerOp);
        } else if (type == CommandType.Console) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), replace);
        }
    }

    public static List<CommandEntry> parseCommands(List<String> list) {
        List<CommandEntry> commands = new ArrayList<>();
        for (String command : list) {
            String[] parts = command.split(":", 2);
            if (parts.length == 2) {
                CommandType type = CommandType.getCommandType(parts[0]);
                String cmd = parts[1];
                commands.add(new CommandEntry(type, cmd));
            }
        }
        return commands;
    }

    @Override
    public String toString() {
        return "CommandEntry{" +
                "type=" + type +
                ", command='" + command + '\'' +
                '}';
    }

}
